<template>
<div style=" display: flex;">
  <div class="search-area">
    <div style="padding: 0 10px">
      <el-form :inline="true" class="demo-form-inline" :model="searchform">
        <el-form-item v-for="(input,index) in _search" :key="index" :label="input.label">
          <el-input
              clearable
              size="small"
              v-if="input.type=='text'"
              v-model="searchform[input.model]"
              :placeholder="input.label"
          ></el-input>

          <el-autocomplete
              clearable
              v-if="input.type=='autocomplete'"
              v-model="searchform[input.model]"
              :placeholder="input.label"
              :disabled="isDisabled(input)"
              :fetch-suggestions="(queryString,cb) => {querySearchAsync(queryString,cb,input.api,input)}"
              @select="handleSelect"
          ></el-autocomplete>

          <el-select
              size="small"
              v-if="input.type=='select'"
              v-model="searchform[input.model]"
              :placeholder="input.label"
              clearable
              filterable>
            <el-option
                v-for="(select,index) in input.options"
                :key="index"
                :label="select.label"
                :value="select.value"
            ></el-option>
          </el-select>

          <el-date-picker
              size="small"
              clearable
              v-if="input.type=='date_year'"
              type="year"
              :placeholder="input.label"
              v-model="searchform[input.model]"
              :value-format="'yyyy'"
          ></el-date-picker>

          <el-date-picker
              size="small"
              :clearable="(search[input.model].clearable == undefined || search[input.model].clearable == true) ? true : false"
              v-if="input.type=='date_month'"
              type="month"
              :placeholder="input.label"
              v-model="searchform[input.model]"
              :value-format="search[input.model].format ? search[input.model].format : 'yyyy-MM'"
          ></el-date-picker>

          <el-date-picker
              size="small"
              :clearable="(search[input.model].clearable == undefined || search[input.model].clearable == true) ? true : false"
              v-if="input.type=='date_date'"
              type="date"
              :placeholder="input.label"
              v-model="searchform[input.model]"
              :value-format="search[input.model].format ? search[input.model].format : 'yyyy-MM-dd'"
          ></el-date-picker>

          <el-select
              size="small"
              v-if="input.type=='select_multiple'"
              clearable
              multiple
              v-model="searchform[input.model]"
              :placeholder="input.label"
          >
            <el-option
                v-for="(item,o) in input.options"
                :key="o"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>

          <el-form-item v-if="input.type=='like_checkbox'">
            <el-checkbox v-model="searchform[input.model]">{{search[input.model].value}}</el-checkbox>
          </el-form-item>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch" size="mini" style="background: #d4a869;border-color: #d4a869">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</div>
</template>

<script>
import qs from "qs";

export default {
  props:['search','download','download2','showPageTitle'],
  name: "XSearch",
  data(){
    return{
      searchform:{}
    }
  },

  created() {
    let data = {}
    Object.keys(this.search).forEach(key => {
      if (this.search[key]['type'] == 'select_multiple'){
        //下拉多选
        data[key] = []
      }else {
        data[key] = this.search[key].defaultValue != undefined ? this.search[key].defaultValue : ''
      }
    });
    this.searchform = data
  },

  computed:{
    _search(){
      let newsearch = [];
      Object.keys(this.search).forEach(key => {
        if (typeof this.search[key] === "string") {
          newsearch.push({
            type: "text",
            label: this.search[key],
            model: key
          });
        } else {
          this.search[key]["model"] = key;
          newsearch.push(this.search[key]);
        }
      });
      return newsearch;
    },

    searchProps(){
      return this.search
    }
  },

  watch:{
    searchProps(){
      let lastSearchform = JSON.parse(JSON.stringify(this.searchform))
      let data = {}
      Object.keys(this.search).forEach(key => {
        if (this.search[key]['type'] == 'select_multiple'){
          //下拉多选
          data[key] = lastSearchform[key] || []
        }else {
          data[key] = lastSearchform[key] || ''
        }
      });
      this.searchform = data
    }
  },

  methods:{
    //返回最终的查询参数
    callSearchform(deleteEmpty=false){
      let data = Object.assign({},this.searchform)
      Object.keys(this.search).forEach(key => {
        //解决月份删除后，elementUI自动设置null
        if (data[key] == null){
          data[key] = ''
        }
        //去除【模糊/精准】字段
        if (typeof this.search[key] !== "string") {
           if (this.search[key] && this.search[key].type === 'like_checkbox'){
              if (this.searchform[key]){
                data[this.search[key]['replaceField']['fieldTo']] = data[this.search[key]['replaceField']['fieldFrom']]
                delete data[this.search[key]['replaceField']['fieldFrom']]
              }
              delete data[key]
           }
        }
      });

      //deleteEmpty 针对dmp系统，去除空参数，否则会一起查询
      if (deleteEmpty){
        let deletDdata = {}
        Object.keys(data).forEach(key => {
          if (data[key].toString().trim() != ''){
            deletDdata[key] = data[key]
          }
        });
        return deletDdata
      }

      return data
    },

    onSearch(){
      console.log(JSON.stringify(this.searchform))
      this.$emit('searchFn',Object.assign({},this.callSearchform()))
    },

    querySearchAsync(queryString, cb, api,input) {
      //最终数据要是[{value:xx,....}] 必须带value
      console.log(JSON.stringify(input))
      let args = {keyword:queryString}
      if (input.useBefore){
        if (this.searchform[input.useBefore.name] == ''){
          cb([]);
          this.$message('请先填写 '+input.useBefore.label);
          return
        }else {
          let keyword = {}
          keyword[input['useBefore']['keyWord']] = this.searchform[input.useBefore.name]
          Object.assign(args,keyword)
        }
      }
      this.$http[api](args).then((res) => {
        if (res && res.code == 200) {
          let newArr = [];
          ([...res.data.list]).map(l => newArr.push({value:l[input.format.label]}))
          cb(newArr);
        }
      });
    },

    handleSelect(item) {
      console.log(JSON.stringify(item));
    },

    //针对上一级未填写，下一级不让填
    isDisabled(input){
      if (input.useBefore && (this.searchform[input.useBefore.name]).trim() == ''){
          this.searchform[input.model] = ''
          return true
      }
      return false
    },

    onDownload(){
      if (this.download.type === 'call'){
        this.$emit('downloadFn',Object.assign({},this.callSearchform()))
      }else {
        window.open(`${this.download.path}?${qs.stringify(Object.assign(this.download.query,this.callSearchform()))}`);
      }
    },

    onDownload2(){
      if (this.download2.type === 'call'){
        this.$emit('download2Fn',Object.assign({},this.callSearchform()))
      }else {
        window.open(`${this.download2.path}?${qs.stringify(Object.assign(this.download2.query,this.callSearchform()))}`);
      }
    }
  }
}
</script>

<style scoped>
.search-area{
  background: #fff;
  border: 5px #e9eef2 solid;
  width: 100%;
  min-height: 100px;
  padding: 5px 0;
  flex:1;
}

>>> .el-form > .el-form-item{
  margin-bottom: 5px;
}

>>>.el-form-item__label{
  font-size: 12px;
  color: #898a8d;
  font-weight: bold;
}
</style>
